import {useState} from 'react'
import {connect, ConnectedProps} from 'react-redux'
import {
  incrementAction,
  decrementAction,
  incrementAsyncAction
} from '../../redux/actions/counter'
import {RootState} from '../../redux/reducers'

// 执行connect函数返回连接器函数
// connector绑定要传递Counter组件的4个属性
const connector = connect(
  // 指定一般属性
  (state: RootState) => ({count: state.counter.count}),
  // 指定函数属性
  /* dispatch =>({
    dispatchIncrement: num => dispatch(incrementAction(num)),
    dispatchDecrement: num => dispatch(decrementAction(num)),
    dispatchIncmentAsync: num => dispatch(incrementAsyncAction(num)),
  })  */
  {
    dispatchIncrement: incrementAction,
    dispatchDecrement: decrementAction,
    dispatchIncmentAsync: incrementAsyncAction
  }
)

// 根据connector函数的类型, 利用redux提供 ConnectedProps类型来决定Counter需要的属性的结构
type Props = ConnectedProps<typeof connector>

function Counter({
  count,
  dispatchIncrement,
  dispatchDecrement,
  dispatchIncmentAsync
}: Props) {

  // 读取store中state的count
  // const {count} = store.getState()

  // const [count, setCount] = useState(0)

  const [num, setNum] = useState(1)

  function increment () {
    // 分发增加的action, 来更新count
    // store.dispatch(incrementAction(num))
    dispatchIncrement(num)
  }
  function decrement () {
    // 分发减少的action, 来更新count
    // store.dispatch(decrementAction(num))
    dispatchDecrement(num)
  }
  function incrementIfOdd () {
    if (count%2===1) {
      increment()
    }
  }
  function incrementAsync () {
    /* setTimeout(() => {
      increment()
    }, 1000); */
    // setTimeout(increment, 1000)
    // 分发异步action (函数类型的action)
    // store.dispatch(incrementAsyncAction(num))  
    dispatchIncmentAsync(num)
  }

  return (
    <>
      <h3>点击次数: {count}</h3>
      <select value={num} onChange={e => setNum(+e.target.value)}>
        <option value="1" key="a">1</option>
        <option value="2" key="b">2</option>
        <option value="3" key="c">3</option>
      </select>
      <button onClick={increment}>增加</button>
      <button onClick={decrement}>减少</button>
      <button onClick={incrementIfOdd}>奇数增加</button>
      <button onClick={incrementAsync}>延迟1S增加</button>
    </>
  )
}


export default connector(Counter)